<template>
	<!-- 小程序需要使用 v-show 而不是 v-if 保证结构存在 -->
	<view
		class="lmm-popup"
		v-show="visible"
		@touchmove.stop.prevent="stopScroll"
	>
		<!-- 蒙层 -->
		<view
			class="lmm-mask"
			:style="{ backgroundColor: maskBackground }"
			@tap="maskClosable && close()"
		></view>

		<!-- 内容区域 -->
		<view
			class="lmm-content"
			:class="[positionClass]"
			:style="contentStyle"
			@tap.stop=""
		>
			<slot></slot>
		</view>
	</view>
</template>

<script>
export default {
	name: 'lmm-popup',
	props: {
		visible: {
			type: Boolean,
			default: false,
		},
		maskBackground: {
			type: String,
			default: 'rgba(0, 0, 0, 0.5)',
		},
		maskClosable: {
			type: Boolean,
			default: true,
		},
		position: {
			type: String,
			default: 'center',
			validator: (value) => ['center', 'bottom'].includes(value),
		},
		width: {
			type: [String, Number],
			default: '80%',
		},
		backgroundColor: {
			type: String,
			default: '#ffffff',
		},
		borderRadius: {
			type: [String, Number],
			default: '12rpx',
		},
		padding: {
			type: [String, Number],
			default: '30rpx',
		},
	},
	computed: {
		positionClass() {
			return `lmm-${this.position}`;
		},
		contentStyle() {
			return {
				width: this.formatUnit(this.width),
				backgroundColor: this.backgroundColor,
				borderRadius: this.formatUnit(this.borderRadius),
				padding: this.formatUnit(this.padding),
			};
		},
	},
	methods: {
		formatUnit(value) {
			if (typeof value === 'number') {
				return value + 'rpx';
			}
			return value;
		},
		close() {
			this.$emit('update:visible', false);
			this.$emit('close');
		},
		stopScroll(e) {
			// 阻止滚动穿透
			return false;
		},
	},
};
</script>

<style lang="scss" scoped>
.lmm-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 999;
}

.lmm-mask {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
}

.lmm-content {
	position: fixed;
	z-index: 1000;
	box-sizing: border-box;
	animation: fadeIn 0.3s;
	left: 50%;
	transform: translateX(-50%);
}

.lmm-center {
	top: 50%;
	transform: translate(-50%, -50%);
}

.lmm-bottom {
	bottom: 0;
	top: auto;
	transform: translateX(-50%);
	width: 100% !important;
	border-bottom-left-radius: 0 !important;
	border-bottom-right-radius: 0 !important;
}

// @keyframes fadeIn {
// 	from {
// 		opacity: 0;
// 		transform: translate(-50%, 20px);
// 	}
// 	to {
// 		opacity: 1;
// 		transform: translate(-50%, 0);
// 	}
// }
</style>